//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace TridentBlackBoardService
{
    using System;
    using System.Configuration;
    using System.Linq;
    using System.ServiceProcess;
    using Microsoft.Practices.EnterpriseLibrary.Logging;
    using Microsoft.Research.eResearch.Blackboard;
    using Microsoft.Research.eResearch.Common.Logging;

    /// <summary>
    /// Contains functionality for the BlackboardServiceHost.
    /// </summary>
    partial class BlackboardServiceHost : ServiceBase
    {
        /// <summary>
        /// The blackboard object.
        /// </summary>
        private Blackboard blackboard;

        /// <summary>
        /// Specifies whether we want to log the debug events as well
        /// </summary>
        private bool isBlackBoardTraceEnabled = false;

        /// <summary>
        /// Initializes a new instance of the BlackboardServiceHost class.
        /// </summary>
        public BlackboardServiceHost()
        {
            InitializeComponent();
        }

        /// <summary>
        /// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
        /// </summary>
        /// <param name="args">Data passed by the start command.</param>
        protected override void OnStart(string[] args)
        {
            Log("Info", "Attempting to start the Blackboard...");
            try
            {
                if (ConfigurationManager.AppSettings.AllKeys.Contains("BlackBoardTraceEnabled"))
                {
                    if (!bool.TryParse(ConfigurationManager.AppSettings["BlackBoardTraceEnabled"], out isBlackBoardTraceEnabled))
                    {
                        isBlackBoardTraceEnabled = false;
                    }
                }

                this.blackboard = new Blackboard();
                this.blackboard.LogMessageReceived += this.BlackboardLogMessageReceived;
                this.blackboard.Start();
            }
            catch (Exception ex)
            {
                Log("Error", ex.ToString());
            }

            Log("Info", "Blackboard started successfully.");
        }

        /// <summary>
        /// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
        /// </summary>
        protected override void OnStop()
        {
            Log("Info", "Attempting to stop the Blackboard...");

            try
            {
                this.blackboard.LogMessageReceived -= this.BlackboardLogMessageReceived;
                this.blackboard.Stop();
                this.blackboard = null;
            }
            catch (Exception ex)
            {
                Log("Error", ex.ToString());
            }

            Log("Info", "Blackboard stopped successfully.");
        }

        /// <summary>
        /// Handles the log message received.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Microsoft.Research.eResearch.Common.Logging.LogEventArgs"/> instance containing the event data.</param>
        private void BlackboardLogMessageReceived(object sender, LogEventArgs e)
        {
            if (!isBlackBoardTraceEnabled &&
             e.Level.Equals("debug", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }
            Log(e.Level, e.Message);
        }

        /// <summary>
        /// Logs the specified log message.
        /// </summary>
        /// <param name="level">The level.</param>
        /// <param name="message">The message.</param>
        private static void Log(string level, string message)
        {
            Logger.Write(message, "FileLoggerBlackboardService");
        }
    }
}
